<template>
  <div class="main">

    <!--    <div class="chat-header" @click="goBack()">-->
    <!--      <i class="el-icon-arrow-left"></i>-->
    <!--      返回-->
    <!--    </div>-->
    <van-sticky>
      <div class="header">
        <div>咨询</div>
        <div style="position: absolute;right: 15px;display: flex">
          <div class="search" @click="gotoHistory()"></div>
          <div class="search scanner" @click="gotoScanner()"></div>
        </div>
      </div>
    </van-sticky>
    <div class="body" id="chatScrollBox">
      <!--      <van-list-->
      <!--          v-model="loading"-->
      <!--          :finished="finished"-->
      <!--          :finished-text="dataList.length == 0 ? '暂无数据' : '没有更多了'"-->
      <!--          @load="onLoad">-->
      <div style="background: #ffffff">
        <div class="card" @click="gotoGfku()">
          <van-image class="avatar" round :src="logo"/>
          <div class="des">
            <div style="font-size: 18px;font-weight: 500;">
              <span>百合医客服</span>
              <span style="width: 27px;
height: 15px;
opacity: 1;
border-radius: 4px;
background: rgba(242, 150, 0, 1);font-size: 12px;
font-weight: 400;
line-height: 17.38px;
color: rgba(255, 255, 255, 1);margin-left: 5px;">官方</span>
            </div>
            <div style="font-size: 12px;font-weight: 400;margin-top: 10px;">{{ bhyLastContent || '没有新消息' }}</div>
          </div>
          <div class="count" v-if="num>0">{{ num }}</div>
          <!--          <img :src="backRight" style="width: 10px;height: 13px;" :class="{'marginAuto':num<=0}"/>-->
        </div>
        <div class="card" @click="gotoShopOffic()">
          <van-image class="avatar" round :src="shopName"/>
          <div class="des">
            <div style="font-size: 18px;font-weight: 500;">商家客服信息</div>
            <div style="font-size: 12px;font-weight: 400;margin-top: 10px;">{{ shopLastContent || '没有新消息' }}</div>
          </div>
          <div class="count" v-if="shopnum>0">{{ shopnum }}</div>
          <img :src="backRight" style="width: 10px;height: 13px;" :class="{'marginAuto':shopnum<=0}"/>
        </div>
        <div class="card" @click="gotoFans">
          <van-image class="avatar" round :src="newFans"/>
          <div class="des">
            <div style="font-size: 18px;font-weight: 500;">粉丝</div>
            <div style="font-size: 12px;font-weight: 400;margin-top: 10px;">没有新消息</div>
          </div>
          <div class="count" v-if="numberNewFans>0">{{ numberNewFans }}</div>
          <img :src="backRight" style="width: 10px;height: 13px;" :class="{'marginAuto':numberNewFans<=0}"/>
        </div>
        <div class="card" @click="gotoOnline()">
          <van-image class="avatar" round :src="onlineWz"/>
          <div class="des">
            <div style="font-size: 18px;font-weight: 500;">在线问诊</div>
            <div style="font-size: 12px;font-weight: 400;margin-top: 10px;">没有新消息</div>
          </div>
          <!--          <div class="count" v-if=""></div>-->
          <img :src="backRight" style="width: 10px;height: 13px;margin-left: auto;"/>
        </div>
      </div>
      <div style="background: #ffffff;margin-top: 10px;">
        <div class="card" v-for="(item,index) in chatList" :key="index" @click="handleActiveItem(item,index)"
             :class="{ 'last-item': index === chatList.length - 1 }" v-show="item.showName.startsWith(keyWord)">
          <van-image class="avatar" round :src="item.headImage?store.state.imgUrl+item.headImage:logo"/>
          <div class="des">
            <div style="display:flex;align-items: center;position: relative">
              <div style="font-size: 18px;font-weight: 500;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-block;" v-if="item.note">
                {{ item.note }}
              </div>
              <div style="font-size: 18px;font-weight: 500;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-block;
" v-else>{{ item.showName }}
              </div>
              <div style="border-radius: 4px;background: rgba(199, 199, 199, 1);margin-left: 8px;padding: 2px;"
                   v-if="item.tag!=='null'&&item.tag!=='' && item.tag !==null">
                {{ item.tag }}
              </div>
            </div>
            <div style="font-size: 12px;font-weight: 400;margin-top: 10px;">{{ item.lastContent || '没有新消息' }}</div>
          </div>
          <div class="count" v-if="parseInt(item.unreadCount)>0">{{ item.unreadCount }}</div>
          <div v-else style="font-size: 12px;font-weight: 400;color: rgba(166, 166, 166, 1);margin-left: auto">
            {{ item.lastSendTime }}
          </div>
        </div>
      </div>
      <!--      </van-list>-->
      <div class="card-zero" v-if="chatStore.chats.length<=0">
        <div style="text-align: center">暂无更多好友数据</div>
      </div>
    </div>
  </div>
</template>

<script>
import httpRequest from "@/api/httpRequest";
import chatStore from "@/store/modules/chatStore";
import router from "@/router";
import {queryStatisticalInfo} from "@/api/my";
import {mapState} from "vuex";
import store from '@/store'

export default {
  name: "customer_consultation",
  data() {
    return {
      store: store,
      type: '',
      keyWord: '',
      logo: require("@/assets/tx.png"),
      backRight: require('@/assets/shopping/back-right.png'),
      onlineWz: require('@/assets/chat/onlineWz.png'),
      shopName: require('@/assets/chat/shopname.png'),
      newFans: require('@/assets/chat/newFans.png'),
      userList: [],
      dealerId: '',
      permissions: [],
      accountCode: '',
      loading: false,
      dataList: [],
      finished: false,
      current: 0,
      namelogon:null,
      chatList: [],
      numberNewFans: 0, //新增粉丝数
      result: ''
    }
  },
  created() {
          console.log("进入了页面咨询")
    this.namelogon= this.$loading({
          lock: true,
          text: '拼命加在中..',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
    this.getChatList().then((res) => {
      console.log('请求列表，数据变换')
      this.$store.commit('setYaseeList', res.records)
    });
    this.queryStatisticalInfo()
  },
  mounted() {
    //v.0.1.1新需求 添加官方客服 商家客服信息 粉丝 在线问诊
    //获取好友列表
    window["getInfoFromFlutter"] = (info) => {
      if (JSON.parse(info).action === 'scanQR') {
        this.result = JSON.parse(info).param.result
        this.getInfoFromFlutter(info);
      }
    };
    // this.$store.commit("initStore"); //好友列表
  },
  computed: {
    chatStore() {
      return this.$store.state.chatStore
    },
    num() {
      return this.$store.state.chatStore.num;
    },
    shopnum() {
      return this.$store.state.chatStore.shopnum
    },
    bhyLastContent() {
      return this.$store.state.chatStore.bhyLastContent
    },
    shopLastContent() {
      return this.$store.state.chatStore.shopLastContent
    },
    ...mapState(['userInfo']),
  },
  watch: {
    'chatStore.chats': {
      handler(newChats, oldChats) {
        console.log('监听到数据变化 list', newChats.length);
        if (newChats.length > 0) {
          let chats = this.chatStore.chats
          this.$nextTick(() => {
            this.chatList = chats
          })
        }
      },
      deep: true
    }
  },
  methods: {
    getParam(name) {
      if (this.result) {
        const query = this.result
        const vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
          var pair = vars[i].split("=");
          if (pair[0] == name) {
            return pair[1];
          }
        }
      } else {
        return "";
      }

    },
    getInfoFromFlutter(info) {
      let data = JSON.parse(info);
      // this.result = data.param.result;
      if (data.action == "scanQR" && data.param && data.param.result) {
        // 3、存储到store里
        // this.result = data.param.result;
        const url = this.getParam('url') ? this.getParam('url') : ''
        let data = {
          name: this.getParam('name') ? this.getParam('name') : '',
          phone: this.getParam('phone') ? this.getParam('phone') : '',
          userId: this.getParam('userId') ? this.getParam('userId') : ''
        }
        if (url) {
          this.$router.push({
            path: "/" + url,
            query: data
          })
        }
       
      }
    },
    queryStatisticalInfo() {
      let data = {
        isOneself: 0,
        authorId: this.userInfo.userId
      }
      queryStatisticalInfo(data).then(res => {
        // this.buttonStatus = res.data.buttonStatus
        this.numberNewFans = res.data.numberNewFans
        setTimeout(() => {
            this.namelogon.close();
        }, 1000);
      })
    },
    //处理官方客服
    gotoGfku() {
      this.$router.push({path: '/bhyOffic'})
      this.$store.state.chatStore.num = 0
      let message = {
        action: 'hiddenBottom',
        param: {}
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
    //在线问诊
    gotoOnline() {
      this.$toast('正在建设中')
    },
    gotoScanner() {
      // this.$toast('正在建设中')
      let message = {
        action: 'scanQR',
        param: {}
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
    //粉丝
    gotoFans() {
      this.$router.push({path: '/addFriend'})
      let message = {
        action: 'hiddenBottom',
        param: {}
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
    //跳转到 商家客服
    gotoShopOffic() {
      this.$router.push({path: '/shopList'})
      this.$store.state.chatStore.shopnum = 0
      let message = {
        action: 'hiddenBottom',
        param: {}
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
    gotoHistory() {
      this.$router.push({path: '/historySearch'})
      let message = {
        action: 'hiddenBottom',
        param: {}
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
    async onLoad() {
      this.current += 1
      this.dataList = await this.getChatList()
      if (this.dataList.length === 0) {
        this.loading = true
      } else {
        this.$store.commit('addYaseeList', this.dataList);
      }
    },
    getChatList() {
      let query = {
        current: this.current,
        size: 100
      }
      return new Promise((resolve, reject) => {
        httpRequest({
          url: `/friend/cmsFriends`,
          method: 'get',
          params: query
        }).then((res) => {
          resolve(res)
        })
      })
    },
    goBack() {
      this.$router.go(-1)
    },
    async handleActiveItem(chat, index) {
      this.$store.commit("activeChat", index,);
      this.$router.push({path: '/chat', query: {chat: chat, accountCode: this.accountCode}})
      let message = {
        action: 'hiddenBottom',
        param: {}
      }
      getInfoFromVue.postMessage(JSON.stringify(message))
    },
  },
}
</script>

<style scoped lang="less">
.main {
  width: 100%;
  height: 100vh;

  .chat-header {
    font-size: 15px;
    padding: 10px;
    height: 20px;
    line-height: 20px;
    border-top: 1px solid #f0f0f0;
    background: #1989fa;
    color: #ffffff;
  }

  .header {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 15px;
    height: 44px;
    background: rgba(242, 150, 0, 1);
    font-size: 20px;
    font-weight: 500;
    color: rgba(255, 255, 255, 1);
    border-top: #ffffff;
    position: relative;

    .search {
      width: 18px;
      height: 18px;
      background-repeat: no-repeat;
      background-position: center;
      background-size: cover;
      background-image: url("../../assets/chat/search.png");
    }

    .scanner {
      background-image: url("../../assets/chat/scanner.png");
      margin-left: 10px;
    }
  }

  .body {
    //margin: 0 15px;
    background: rgba(242, 242, 242, 1);

    .last-item {
      border-bottom: 1px solid #f0f0f0; /* 替换为您想要的底部边框样式 */
    }

    .card-zero {
      margin-top: 10px;
      font-size: 15px;
      padding: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .card {
      //margin-top: 10px;
      font-size: 15px;
      padding: 15px;
      border-top: 1px solid #f0f0f0;

      display: flex;
      align-items: center;
      justify-content: flex-start;

      .avatar {
        width: 52px;
        height: 52px;
      }

      .des {
        margin-left: 10px;

        :nth-child(2) {
          //margin-top: 10px;
          //width: 200px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }

      .marginAuto {
        margin-left: auto;
      }

      .count {
        margin-left: auto;
        margin-right: 10px;
        width: 20px;
        height: 20px;
        line-height: 20px;
        border-radius: 50%;
        background-color: red;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
